package com.thinkingcoder.tccache.core.operator;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.thinkingcoder.tccache.core.model.CacheEntry;

public abstract class AbstractOperator {

    public static long CURRENT = System.currentTimeMillis();

    public static Map<String, CacheEntry<?>> TABLE = new ConcurrentHashMap<>(1024);

    public boolean checkInvalid(String key) {
        CacheEntry<?> cacheEntry = getCacheEntry(key);
        if (cacheEntry == null || cacheEntry.getValue() == null) {
            return true;
        }
        if (cacheEntry.getTimeToLive() > 0 && CURRENT - cacheEntry.getTimestamp() > cacheEntry.getTimeToLive()) {
            System.out.println(String.format("KEY[%S] expire cause CURRENT[%d]-Timestamp[%d] > TimeToLive[%d] ms", key,
                CURRENT, cacheEntry.getTimestamp(), cacheEntry.getTimeToLive()));
            TABLE.remove(key);
            return true;
        }
        return false;
    }

    public static void updateTimestamp() {
        CURRENT = System.currentTimeMillis();
    }

    Map<String, CacheEntry<?>> getMap() {
        return TABLE;
    }

    CacheEntry<?> getCacheEntry(String key) {
        return TABLE.get(key);
    }

    Object getCacheEntryValue(String key) {
        CacheEntry<?> cacheEntry = getCacheEntry(key);
        if (cacheEntry == null) {
            return null;
        }
        return cacheEntry.getValue();
    }

    void putCacheEntry(String key, CacheEntry<?> cacheEntry) {
        TABLE.put(key, cacheEntry);
    }
}
